import { ref, computed, onMounted } from "vue";
import { useRoute } from "vue-router";
import { getDetail } from "@/api/detail";

import type { IProduct } from "@/api/home";

export function useDetail() {
  // 通过 useRoute 获取当前匹配的路由信息对象，this.$route
  const route = useRoute();
  // const proid = <string>route.params.id; // 类型断言1
  const proid = route.params.id as string; // 类型断崖2

  // 详情数据 Partial 将 IProduct 类型的所有属性变成可选
  const data = ref<Partial<IProduct>>({});
  const banners = computed(() => {
    if (data.value.banners) {
      return data.value.banners[0].split(",");
    } else {
      return [];
    }
    // return data.value.banners[0].split(",");
  });

  // 请求数据的方式
  const fetchData = async () => {
    const response = await getDetail(proid);
    // console.log(response.data);
    // data = response.data; // 会丢失响应

    data.value = response.data;
  };

  onMounted(() => {
    fetchData();
  });

  return {
    proid,
    data,
    banners,
  };
}
